package com.ys.erp.common.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lwj
 * @date 2024/1/18
 */
@Slf4j
@Component
public class JwtUtil {


    /**
     * 创建jwt
     *
     * @param param map参数
     * @return jwt
     */
    public String createToken(@NotNull Map<String, String> param, int calendarField, int calendarInterval, String key) {
        Date iatDate = new Date();
        // expire time
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(calendarField, calendarInterval);
        Date expiresDate = nowTime.getTime();
        // header Map
        Map<String, Object> map = new HashMap<>(8);
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        // build token
        // param backups {iss:Service, aud:APP}
        JWTCreator.Builder builder = JWT.create().withHeader(map);
        param.forEach(builder::withClaim);
        return builder.withIssuedAt(iatDate)
                .withExpiresAt(expiresDate)
                .sign(Algorithm.HMAC256(key));
    }

    /**
     * 解密Token
     *
     * @param token jwt
     * @param  key 密钥
     * @return 解密数据
     * @throws Exception 解析错误
     */
    public Map<String, Claim> verifyToken(String token,String key) throws Exception {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(key)).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
            throw new Exception("token校验错误");
        }
        return jwt.getClaims();
    }

}
